/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
// -*- coding:iso-8859-15 mode: c++ -*-
/** 
 * \file
 * \brief MaCI_SpeedCtrl Logger implementation.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 * $Id: SpeedCtrlLogger.cpp,v 1.11 2009-06-12 12:54:44 morsko Exp $
 *
 */
#include "SpeedCtrlLogger.hpp"
#include "gimutils.h"



SpeedCtrlLogger::SpeedCtrlLogger(MaCI::SpeedCtrl::CSpeedCtrlClient *aClient,
                                 std::string aMaCISLName):
  CSync(1, 1),               
  CThread(1),                
  Logger(),
  iSClient(aClient),
  iRunning(false),
  iRunningThreadStopped(true),
  iFile(NULL),
  iMaCISLName(aMaCISLName),
  iAdditionalInformation("Not active")
{
  if(!iSClient->StartGettingSpeedEvent()){
    dPrint(1,"Failed to start getting speed events.");
  }
}

SpeedCtrlLogger::~SpeedCtrlLogger(){
  if(iRunning){
    StopLogging();
  }
}

 
bool SpeedCtrlLogger::StartLogging(void)
{
  dPrint(1,"Start called");
  if(!iRunning){
    char buffer[256];
    dPrint(5,"Start logging SpeedCtrl speed values");
    if(iFilenameSet){
      sprintf(buffer,"data/%s.txt",
              iFilename.c_str());
     
    }else{
     
      gim::time tstamp(true);
      tm t;
      //      MaCI::Common::TTimestamp tstamp;
      tstamp.getLocalTime(t);
       
        sprintf(buffer,"data/%s_%.2d_%.2d_%d_%.2d:%.2d:%.2d.txt",
              iMaCISLName.c_str(),
              t.tm_mday,
              t.tm_mon+1,
              t.tm_year+1900,
              t.tm_hour,
              t.tm_min,
              t.tm_sec);
              
     
    }
    iFile = fopen(buffer,"wt");
    iRunning = true; 
    RunThread(0);
    return true;
  }

  return false;
}

 
bool SpeedCtrlLogger::StopLogging(void)
{

  dPrint(10,"stop called");
  if(iRunning){
    Lock();
    iRunning = false;
    Unlock();
    WaitThread(0);
    Lock();
    iAdditionalInformation = "Not active";
    Unlock();
    return true;
    
  }
  return false;
}


int SpeedCtrlLogger::ThreadFunction(const int aThreadNumber)
{
  using namespace MaCI::SpeedCtrl;
  if(aThreadNumber == 0){
   
    float speed,angularSpeed,acceleration;
    MaCI::Common::TTimestamp timestamp;
    int seq = -1;
    /////////Search the group and instance names :)
    std::string instance;
    std::string group;
    
    MaCI::MaCICtrl::SMaCISL sl(iMaCISLName);
    if (sl.IsValidFQMaCISL()) {
      group = sl.GetDeviceGroup();
      instance = sl.GetInstance();
    }
    //////////
    
    fprintf(iFile,"%%MaCI_SpeedCtrl log file\n");
    fprintf(iFile,"%%Group: %s Instance: %s\n",group.c_str(),instance.c_str());
    fprintf(iFile,"%%timestamp_s timestamp_us speed angularSpeed acceleration \n\n");
    
    while(iRunning){
      char buffer[256];
      if(iSClient->GetSpeed(speed,
                            angularSpeed,
                            acceleration,
                            timestamp,
                            &seq, 
                            2000)){
        Lock();
        
        fprintf(iFile,"%u %u %f %f %f\n",
                timestamp.timestamp_s,
                timestamp.timestamp_us,
                speed,
                angularSpeed,
                acceleration);
          
        
        fflush(iFile);
        sprintf(buffer,"s: %u, us: %u, speed %.2f angularSpeed: %.2f acceleration %.2f",
                timestamp.timestamp_s,timestamp.timestamp_us,
                speed,angularSpeed,acceleration);
        iAdditionalInformation.clear();
        iAdditionalInformation.assign(buffer);
        Unlock();
      }else{
        dPrint(1,"No speed event...");
      }
    }
    
    Lock();
    iRunningThreadStopped = true;
    Unlock();
    
  }

  return 0;

}

std::string SpeedCtrlLogger::GetName(){
  return "SpeedCtrl Logger";
}

bool SpeedCtrlLogger::GetAdditionalInformation(std::string &aInformation){
  Lock();
  aInformation = iAdditionalInformation;
  Unlock();
  return true;
}
